package com.fuyao.cloud.admin.flow.actor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fuyao.cloud.flowable.entity.ActorUser;
import com.fuyao.cloud.admin.api.entity.SysUser;
import com.fuyao.cloud.flowable.vo.ActorInstance;
import com.fuyao.cloud.admin.service.SysUserService;
import com.fuyao.cloud.common.security.service.CloudUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;


@Slf4j
@ActorTypeCodeAnnotation("AT_USER")
@Component
public class ActorTypeAtUser implements ActorTypeFactory {

    @Autowired
    public SysUserService userService;

    @Override
    public List<ActorInstance> execute(CloudUser user, ActorUser actorUser, String procInstId) {
        log.info("AT_USER : actorId:{}, procInstId:{}", actorUser.getActorId(), procInstId);

        // 为空直接返回
        if (ObjectUtil.isEmpty(actorUser) || StrUtil.isEmpty(actorUser.getActorId())) {
            return Lists.newArrayList();
        }

        if(StrUtil.isEmpty(actorUser.getParams())){
            return Lists.newArrayList();
        }
        LambdaQueryWrapper<SysUser> userLambdaQueryWrapper = Wrappers.<SysUser>lambdaQuery().in(SysUser::getUsername, StrUtil.split(actorUser.getParams(), ";"));
        List<SysUser> userList = userService.list(userLambdaQueryWrapper);

        // TODO: 优化为自定义异常
        if(CollUtil.isEmpty(userList)){
            throw new RuntimeException("AT_USER : actorId:"+ actorUser.getActorId() +" 配置用户未找到");
        }
        SysUser sysUser = CollUtil.getFirst(userList);
        ActorInstance actorInstance = new ActorInstance(sysUser);
        return Collections.singletonList(actorInstance);
    }
}
